﻿using System;
using System.IO;

class SquareMatrixOfNumbers
{
    static void Main()
    {
        //Exercise 5.
        //Write a program that reads a text file containing a square matrix of numbers and finds in the matrix an area of 
        //size 2 x 2 with a maximal sum of its elements. The first line in the input file contains the size of matrix N. 
        //Each of the next N lines contain N numbers separated by space. The output should be a single number in a separate 
        //text file. Example:
        //4
        //2 3 3 4
        //0 2 3 4		->	17
        //3 7 1 2
        //4 3 3 2

        StreamReader reader = new StreamReader(@"C:\Users\Toni\Desktop\Test Matrix.txt");
        StreamWriter writer = new StreamWriter(@"C:\Users\Toni\Desktop\Test Matrix Result.txt");

        int matrixLength = 0;
        int resultBestSum = 0;
        
        using (reader)
        {
            string lineN = reader.ReadLine();    //reads the first line that is the size of the matrix
            matrixLength = int.Parse(lineN);

            int[,] matrix = new int[matrixLength, matrixLength];    //create a square matrix

            lineN = reader.ReadLine();          //reads the next line

            int lineNumber = 0;
            while (lineN != null)
            {
                lineNumber++;
                string[] matrixElement = lineN.Split(' ');  //create a string array for each line of the matrix
                for (int i = 0; i < matrix.GetLength(0); i++)
                {
                    matrix[lineNumber - 1, i] = int.Parse(matrixElement[i]);
                }
                
                lineN = reader.ReadLine();
            }

            resultBestSum = MaximalSum(matrix);
        }

        using (writer)            //writing the maximal sum in a new text-file
        {
            writer.Write(resultBestSum);
        }

        Console.WriteLine("File is written!");
    }

    private static int MaximalSum(int[,] matrix)
    {
        int bestSum = int.MinValue;        
        for (int row = 0; row < matrix.GetLength(0) - 1; row++)
        {
            for (int col = 0; col < matrix.GetLength(1) - 1; col++)
            {
                int sum = 0;
                sum = matrix[row, col] + matrix[row + 1, col] +
                    matrix[row, col + 1] + matrix[row + 1, col + 1];
                if (sum >= bestSum)
                {
                    bestSum = sum;                    
                }
            }
        }
        return bestSum;
    }
}

